import click
from flask.cli import with_appcontext
from app import db
from sqlalchemy import text

@click.command('init-db')
@with_appcontext
def init_db_command():
    """Clear existing data and create new tables."""
    db.create_all()
    click.echo('Initialized the database.')

@click.command('check-db')
@with_appcontext
def check_db_command():
    """检查数据库连接和表状态"""
    try:
        # 检查连接
        db.session.execute(text('SELECT 1'))
        click.echo('数据库连接正常')
        
        # 获取所有表名
        inspector = db.inspect(db.engine)
        tables = inspector.get_table_names()
        
        click.echo('\n现有数据表:')
        for table in tables:
            click.echo(f'- {table}')
            # 获取表的列信息
            columns = inspector.get_columns(table)
            for column in columns:
                click.echo(f'  * {column["name"]}: {column["type"]}')
        
        # 检查表中的记录数
        click.echo('\n表记录统计:')
        for table in tables:
            result = db.session.execute(text(f'SELECT COUNT(*) FROM {table}')).scalar()
            click.echo(f'- {table}: {result} 条记录')
            
        # 显示数据库配置信息
        from flask import current_app
        db_url = current_app.config['SQLALCHEMY_DATABASE_URI']
        # 隐藏敏感信息
        if '@' in db_url:
            db_url = db_url.split('@')[1]
        click.echo(f'\n数据库URL: {db_url}')
        
    except Exception as e:
        click.echo(f'数据库检查失败: {str(e)}', err=True)

def init_app(app):
    app.cli.add_command(init_db_command)
    app.cli.add_command(check_db_command) 